import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as actions from '../actions/index'

class Home extends Component {

    componentDidMount() {
        if(!this.props.list || !this.props.list.length) {
            this.props.add_List()
        }
    }

    addItem() {
        this.props.history.push({
            pathname: '/add',
            state: {
                flag: false
            }
        })
    }

    deleteItem(index) {
        this.props.delete_Item(index)
    }

    editItem(item) {
        this.props.history.push({
            pathname: '/add',
            state: {
                item,
                flag: true
            }
        })
    }

    render() { 
        console.log(this.props.list)
        let { list } = this.props
        return (
            <div>
                {
                    list && list.length ? list.map((item,index) => {
                        return (
                            <div key={index}>
                                <p>姓名：{item.name}</p>
                                <p>地址：{item.city}</p>
                                <button onClick={
                                    this.editItem.bind(this,item)
                                }>编辑</button>
                                <button onClick={
                                    this.deleteItem.bind(this, index)
                                }>删除</button>
                            </div>
                        )
                    }) : <div>暂无数据</div>
                }
                <button style={{marginTop: '50px'}} onClick={
                    this.addItem.bind(this)
                }>添加</button>
            </div>
        )
    }3
}

let mapStateToProps = ({addReducer}) => {
    return {
        ...addReducer
    }
}

let mapDispatchToProps = (dispatch) => bindActionCreators(actions, dispatch)
 
export default connect(mapStateToProps, mapDispatchToProps)(Home)